package cn.wolfcode.crm.util;

//日志工具类

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class SystemLogAspcet {

    @Setter
    private ISystemLogService service;

    public void writer(JoinPoint jp) throws JsonProcessingException
    {
        //应为日志记录是切入到service层的，不需要做日志记录的记录
        if(jp.getTarget() instanceof ISystemLogService)
        {
            return;
        }

        //用来将数据封装层对象
        SystemLog sytemLog = new SystemLog();
        sytemLog.setOpTime(new Date());
        //获取到当前操作的用户对象
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        sytemLog.setOpUser(employee);
        //获取到当前执行的方法
        sytemLog.setFunction(jp.getTarget().getClass().getName() + ":" + jp.getSignature().getName());
        //获取当前使用的参数
        sytemLog.setParams(new ObjectMapper().writeValueAsString(jp.getArgs()));

        //获取到当前的请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //获取到真实的ip地址
        String ip = request.getHeader("x-forwarded-for");

        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
        }

        sytemLog.setOpIp(ip);

        service.insert(sytemLog);
    }
}
